import tkinter as tk
from tkinter import ttk, scrolledtext, filedialog, messagebox
import os
from PIL import Image, ImageTk

class ApplicationView(tk.Tk):
    """应用程序视图"""
    def __init__(self, controller):
        super().__init__()
        self.controller = controller
        self.title("宏自动化工具")
        self.geometry("1000x700")
        self.minsize(800, 600)
        # 设置窗口图标
        icon_path = os.path.join(os.path.dirname(__file__), "icon.ico")
        self.iconbitmap(icon_path)
        
        # 设置中文字体支持
        self.style = ttk.Style()
        # self.style.configure(".", font=("SimHei", 10))
        
        # 不自动创建界面和绑定快捷键
        # self.create_widgets()
        # self.bind_shortcuts()
    
    def create_widgets(self):
        """创建所有界面组件"""
        # 创建菜单栏
        # self.create_menu()
        
        # 创建模式切换
        self.mode_var = tk.StringVar(value="edit")
        mode_frame = ttk.Frame(self)
        mode_frame.pack(fill=tk.X, padx=10, pady=5)
        
        ttk.Radiobutton(
            mode_frame, text="编辑模式（Ctrl+E）", variable=self.mode_var, 
            value="edit", command=lambda: self.controller.switch_mode("edit")
        ).pack(side=tk.LEFT, padx=10)
        
        ttk.Radiobutton(
            mode_frame, text="执行模式（Ctrl+R）", variable=self.mode_var, 
            value="run", command=lambda: self.controller.switch_mode("run")
        ).pack(side=tk.LEFT, padx=10)
        
        # 创建主内容区域
        self.main_frame = ttk.Frame(self)
        self.main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)
        
        # 创建两种模式的界面
        self.create_edit_mode_ui(self.main_frame)
        self.create_run_mode_ui(self.main_frame)

        # 日志区域（放在主界面底部，所有模式都显示）
        log_frame = ttk.Frame(self.main_frame)
        log_frame.pack(side=tk.BOTTOM, fill=tk.X, padx=5, pady=5)
        ttk.Label(log_frame, text="日志:").pack(anchor=tk.W, padx=5, pady=5)
        self.log_text = scrolledtext.ScrolledText(log_frame, wrap=tk.WORD, height=8)
        self.log_text.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
        self.log_text.config(state=tk.DISABLED)
        
        # 默认显示编辑模式
        self.controller.switch_mode("edit")
    
    def create_menu(self):
        """创建菜单栏"""
        menubar = tk.Menu(self)
        
        # 文件菜单
        file_menu = tk.Menu(menubar, tearoff=0)
        file_menu.add_command(label="新建宏", command=self.controller.new_project, accelerator="Ctrl+N")
        file_menu.add_command(label="打开宏", command=self.controller.open_project, accelerator="Ctrl+O")
        file_menu.add_separator()
        
        # 最近文件子菜单
        self.recent_menu = tk.Menu(file_menu, tearoff=0)
        file_menu.add_cascade(label="最近文件", menu=self.recent_menu)
        self.update_recent_menu(self.controller.model.recent_projects)
        
        file_menu.add_separator()
        file_menu.add_command(label="保存宏", command=self.controller.save_project, accelerator="Ctrl+S")
        file_menu.add_command(label="另存为", command=self.controller.save_project_as, accelerator="Ctrl+Shift+S")
        file_menu.add_separator()
        file_menu.add_command(label="退出", command=self.on_close)
        menubar.add_cascade(label="文件", menu=file_menu)
        
        # 编辑菜单
        edit_menu = tk.Menu(menubar, tearoff=0)
        edit_menu.add_command(label="撤销", command=self.controller.undo_action, accelerator="Ctrl+Z")
        edit_menu.add_separator()
        edit_menu.add_command(label="剪切", command=self.controller.cut_action, accelerator="Ctrl+X")
        edit_menu.add_command(label="复制", command=self.controller.copy_action, accelerator="Ctrl+C")
        edit_menu.add_command(label="粘贴", command=self.controller.paste_action, accelerator="Ctrl+V")
        edit_menu.add_separator()
        edit_menu.add_command(label="删除选中项", command=self.controller.delete_selected_item, accelerator="Del")
        menubar.add_cascade(label="编辑", menu=edit_menu)
        
        # 工具菜单
        tool_menu = tk.Menu(menubar, tearoff=0)
        tool_menu.add_command(label="截图工具", command=self.controller.open_screenshot_tool, accelerator="F8")
        # tool_menu.add_command(label="录制宏", command=self.controller.start_recording)
        # tool_menu.add_command(label="停止录制", command=self.controller.stop_recording)
        menubar.add_cascade(label="工具", menu=tool_menu)
        
        # 帮助菜单
        help_menu = tk.Menu(menubar, tearoff=0)
        help_menu.add_command(label="使用帮助", command=self.controller.show_help)
        help_menu.add_command(label="关于", command=self.controller.show_about)
        menubar.add_cascade(label="帮助", menu=help_menu)
        
        self.config(menu=menubar)
    
    def create_run_mode_ui(self, parent):
        """创建执行模式界面"""
        self.run_frame = ttk.Frame(parent)

        # 左侧宏列表
        left_frame = ttk.Frame(self.run_frame, width=300)
        left_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=False, padx=5, pady=5)

        ttk.Label(left_frame, text="宏命令列表:").pack(anchor=tk.W, padx=5, pady=5)

        # 宏列表
        self.macro_listbox = tk.Listbox(left_frame, selectmode=tk.EXTENDED, height=20)
        self.macro_listbox.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)

        # 滚动条
        scrollbar = ttk.Scrollbar(self.macro_listbox, command=self.macro_listbox.yview)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.macro_listbox.config(yscrollcommand=scrollbar.set)

        # 执行控制按钮
        control_frame = ttk.Frame(left_frame)
        control_frame.pack(fill=tk.X, padx=5, pady=10)

        self.run_button = ttk.Button(
            control_frame, text="运行宏 (F9)", command=self.controller.start_execution, width=10
        )
        self.run_button.pack(side=tk.LEFT, padx=5)

        self.stop_button = ttk.Button(
            control_frame, text="停止 (F10)", command=self.controller.stop_execution, width=10, state=tk.DISABLED
        )
        self.stop_button.pack(side=tk.LEFT, padx=5)

        # 新增循环执行选项
        self.loop_var = tk.BooleanVar(value=False)
        ttk.Checkbutton(
            control_frame, text="循环执行", variable=self.loop_var
        ).pack(side=tk.LEFT, padx=5)

        # 右侧当前执行项属性面板
        right_frame = ttk.Frame(self.run_frame)
        right_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True, padx=5, pady=5)

        ttk.Label(right_frame, text="当前执行项属性:").pack(anchor=tk.W, padx=5, pady=5)
        self.run_properties_frame = ttk.LabelFrame(right_frame, text="属性")
        self.run_properties_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
    
    def create_edit_mode_ui(self, parent):
        """创建编辑模式界面"""
        self.edit_frame = ttk.Frame(parent)
        
        # 左侧模块库和宏列表
        left_frame = ttk.Frame(self.edit_frame, width=300)
        left_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=False, padx=5, pady=5)
        
        # 模块库
        ttk.Label(left_frame, text="模块库:").pack(anchor=tk.W, padx=5, pady=5)
        module_frame = ttk.Frame(left_frame)
        module_frame.pack(fill=tk.X, padx=5, pady=5)
        
        # 宏命令类型按钮
        self.macro_type = tk.StringVar(value="keyboard")
        
        macro_types = [
            ("键盘操作", "keyboard"),
            ("文本输入", "text"),
            ("鼠标移动", "mouse_move"),
            ("移动到图片", "mouse_move_image"),
            ("鼠标操作", "mouse"),
            ("滚轮滚动", "scroll"),
            ("等待", "wait"),
            ("等待按键", "wait_key")
        ]
        
        for i, (text, value) in enumerate(macro_types):
            ttk.Radiobutton(
                module_frame, text=text, variable=self.macro_type, 
                value=value, command=self.controller.update_macro_editor
            ).grid(row=i//2, column=i%2, sticky=tk.W, padx=5, pady=5)
        
        # 宏列表
        ttk.Label(left_frame, text="宏命令列表:").pack(anchor=tk.W, padx=5, pady=5)
        
        self.edit_listbox = tk.Listbox(left_frame, selectmode=tk.SINGLE, height=10)
        self.edit_listbox.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
        self.edit_listbox.bind('<<ListboxSelect>>', self.controller.on_macro_selected)
        
        # 滚动条
        scrollbar = ttk.Scrollbar(self.edit_listbox, command=self.edit_listbox.yview)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.edit_listbox.config(yscrollcommand=scrollbar.set)
        
        # 列表操作按钮
        list_ops_frame = ttk.Frame(left_frame)
        list_ops_frame.pack(fill=tk.X, padx=5, pady=5)
        
        ttk.Button(
            list_ops_frame, text="上移", command=self.controller.move_item_up
        ).pack(side=tk.LEFT, padx=2, fill=tk.X, expand=True)
        
        ttk.Button(
            list_ops_frame, text="下移", command=self.controller.move_item_down
        ).pack(side=tk.LEFT, padx=2, fill=tk.X, expand=True)
        
        ttk.Button(
            list_ops_frame, text="删除", command=self.controller.delete_selected_item
        ).pack(side=tk.LEFT, padx=2, fill=tk.X, expand=True)
        
        # 右侧宏命令编辑区域
        right_frame = ttk.Frame(self.edit_frame)
        right_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True, padx=5, pady=5)
        
        ttk.Label(right_frame, text="宏属性编辑:").pack(anchor=tk.W, padx=5, pady=5)
        
        # 宏命令编辑区域
        self.macro_editor_frame = ttk.LabelFrame(right_frame, text="属性设置")
        self.macro_editor_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
        
        # 添加按钮
        btn_frame = ttk.Frame(right_frame)
        btn_frame.pack(fill=tk.X, padx=5, pady=10)
        
        ttk.Button(
            btn_frame, text="添加到列表", command=self.controller.add_macro_to_list
        ).pack(side=tk.RIGHT, padx=5)
        
        # 选中项属性面板
        self.properties_frame = ttk.LabelFrame(right_frame, text="选中项属性")
        self.properties_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
        
        # 初始显示提示
        ttk.Label(
            self.properties_frame, 
            text="请在左侧列表中选择一个宏命令查看其属性"
        ).pack(anchor=tk.CENTER, expand=True)
    
    def switch_mode(self, mode):
        """切换执行模式和编辑模式"""
        if mode == "run":
            self.edit_frame.pack_forget()
            self.run_frame.pack(fill=tk.BOTH, expand=True)
            self.controller.update_macro_list()
        else:
            self.run_frame.pack_forget()
            self.edit_frame.pack(fill=tk.BOTH, expand=True)
            self.controller.update_edit_list()
            self.controller.update_macro_editor()
    
    def update_macro_editor(self, macro_type):
        """根据选择的宏命令类型更新编辑器"""
        # 清空现有控件
        for widget in self.macro_editor_frame.winfo_children():
            widget.destroy()
        
        common_keys = [
            "enter", "space", "tab", "esc", "shift", "ctrl", "alt",
            "up", "down", "left", "right",
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
            "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
            "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F11", "F12"
        ]
        
        if macro_type == "keyboard":
            # 键盘操作编辑器
            ttk.Label(self.macro_editor_frame, text="按键:").grid(row=0, column=0, sticky=tk.W, padx=5, pady=5)
            self.keyboard_key = tk.StringVar(value="enter")
            ttk.Combobox(
                self.macro_editor_frame, textvariable=self.keyboard_key,
                values=common_keys, state="readonly"
            ).grid(row=0, column=1, padx=5, pady=5)
            ttk.Label(self.macro_editor_frame, text="(仅支持常用键)").grid(row=0, column=2, padx=5, pady=5)
            
            ttk.Label(self.macro_editor_frame, text="操作类型:").grid(row=1, column=0, sticky=tk.W, padx=5, pady=5)
            self.keyboard_action = tk.StringVar(value="Click")
            ttk.Combobox(
                self.macro_editor_frame, textvariable=self.keyboard_action,
                values=["Click", "Press", "Release"], state="readonly"
            ).grid(row=1, column=1, padx=5, pady=5)
            
        elif macro_type == "text":
            # 文本输入编辑器
            ttk.Label(self.macro_editor_frame, text="输入文本:").grid(row=0, column=0, sticky=tk.NW, padx=5, pady=5)
            self.text_content = tk.StringVar()
            ttk.Entry(self.macro_editor_frame, textvariable=self.text_content, width=50).grid(row=0, column=1, padx=5, pady=5)
            
        elif macro_type == "mouse_move":
            # 鼠标移动编辑器
            ttk.Label(self.macro_editor_frame, text="X坐标:").grid(row=0, column=0, sticky=tk.W, padx=5, pady=5)
            self.mouse_x = tk.IntVar(value=0)
            ttk.Entry(self.macro_editor_frame, textvariable=self.mouse_x).grid(row=0, column=1, padx=5, pady=5)
            
            ttk.Label(self.macro_editor_frame, text="Y坐标:").grid(row=1, column=0, sticky=tk.W, padx=5, pady=5)
            self.mouse_y = tk.IntVar(value=0)
            ttk.Entry(self.macro_editor_frame, textvariable=self.mouse_y).grid(row=1, column=1, padx=5, pady=5)
            
            ttk.Button(
                self.macro_editor_frame, text="获取当前鼠标位置（F8）",
                command=self.controller.get_current_mouse_pos
            ).grid(row=2, column=0, columnspan=2, pady=5)
            
        elif macro_type == "mouse_move_image":
            # 移动到图片编辑器
            ttk.Label(self.macro_editor_frame, text="图片文件:").grid(row=0, column=0, sticky=tk.W, padx=5, pady=5)
            self.image_path = tk.StringVar()
            ttk.Entry(self.macro_editor_frame, textvariable=self.image_path, width=40).grid(row=0, column=1, padx=5, pady=5)
            ttk.Button(
                self.macro_editor_frame, text="浏览...",
                command=self.controller.browse_image_file
            ).grid(row=0, column=2, padx=5, pady=5)
            
            ttk.Button(
                self.macro_editor_frame, text="截取图片",
                command=self.controller.capture_image_for_macro
            ).grid(row=1, column=0, columnspan=3, pady=5)
            
            # 显示图片预览
            self.image_preview_label = ttk.Label(self.macro_editor_frame, text="图片预览:")
            self.image_preview_label.grid(row=2, column=0, sticky=tk.W, padx=5, pady=5)
            
            self.image_preview = ttk.Label(self.macro_editor_frame)
            self.image_preview.grid(row=3, column=0, columnspan=3, padx=5, pady=5)
            
            ttk.Label(self.macro_editor_frame, text="灰度匹配:").grid(row=4, column=0, sticky=tk.W, padx=5, pady=5)
            self.image_grayscale = tk.BooleanVar(value=True)
            ttk.Checkbutton(
                self.macro_editor_frame, variable=self.image_grayscale
            ).grid(row=4, column=1, sticky=tk.W, padx=5, pady=5)
            
            ttk.Label(self.macro_editor_frame, text="置信度:").grid(row=5, column=0, sticky=tk.W, padx=5, pady=5)
            self.image_confidence = tk.DoubleVar(value=0.8)
            self.confidence_scale = ttk.Scale(
                self.macro_editor_frame, variable=self.image_confidence,
                from_=0.5, to=1.0, orient=tk.HORIZONTAL, length=200,
                command=lambda v: self.image_confidence.set(round(float(v), 2))
            )
            self.confidence_scale.grid(row=5, column=1, padx=5, pady=5)
            self.confidence_label = ttk.Label(
                self.macro_editor_frame, text=str(round(self.image_confidence.get(), 2))
            )
            self.confidence_label.grid(row=5, column=2, padx=5, pady=5)
            
            # 更新显示的置信度值
            self.image_confidence.trace_add("write", lambda *args: 
                self.confidence_label.config(text=str(round(self.image_confidence.get(), 2)))
            )
            
            # 监听图片路径变化，更新预览
            self.image_path.trace_add("write", self.controller.update_image_preview)
        
        elif macro_type == "mouse":
            # 鼠标操作编辑器
            ttk.Label(self.macro_editor_frame, text="鼠标按键:").grid(row=0, column=0, sticky=tk.W, padx=5, pady=5)
            self.mouse_button = tk.StringVar(value="left")
            ttk.Combobox(
                self.macro_editor_frame, textvariable=self.mouse_button,
                values=["left", "right", "middle"], state="readonly"
            ).grid(row=0, column=1, padx=5, pady=5)
            
            ttk.Label(self.macro_editor_frame, text="操作类型:").grid(row=1, column=0, sticky=tk.W, padx=5, pady=5)
            self.mouse_action = tk.StringVar(value="Click")
            ttk.Combobox(
                self.macro_editor_frame, textvariable=self.mouse_action,
                values=["Click", "Press", "Release"], state="readonly"
            ).grid(row=1, column=1, padx=5, pady=5)
            
        elif macro_type == "scroll":
            # 滚轮滚动编辑器
            ttk.Label(self.macro_editor_frame, text="滚动量:").grid(row=0, column=0, sticky=tk.W, padx=5, pady=5)
            self.scroll_amount = tk.IntVar(value=0)
            ttk.Entry(self.macro_editor_frame, textvariable=self.scroll_amount).grid(row=0, column=1, padx=5, pady=5)
            ttk.Label(self.macro_editor_frame, text="(正数向下，负数向上)").grid(row=0, column=2, padx=5, pady=5)
            
        elif macro_type == "wait":
            # 等待编辑器
            ttk.Label(self.macro_editor_frame, text="等待时间(毫秒):").grid(row=0, column=0, sticky=tk.W, padx=5, pady=5)
            self.wait_time = tk.IntVar(value=1000)
            ttk.Entry(self.macro_editor_frame, textvariable=self.wait_time).grid(row=0, column=1, padx=5, pady=5)
            
        elif macro_type == "wait_key":
            # 等待按键编辑器
            ttk.Label(self.macro_editor_frame, text="等待按键:").grid(row=0, column=0, sticky=tk.W, padx=5, pady=5)
            self.wait_key = tk.StringVar(value="enter")
            ttk.Combobox(
                self.macro_editor_frame, textvariable=self.wait_key,
                values=common_keys, state="readonly"
            ).grid(row=0, column=1, padx=5, pady=5)
            ttk.Label(self.macro_editor_frame, text="(仅支持常用键)").grid(row=0, column=2, padx=5, pady=5)
    
    def update_image_preview(self, file_path):
        """更新图片预览"""
        if hasattr(self, 'image_preview') and file_path and os.path.exists(file_path):
            try:
                img = Image.open(file_path)
                img.thumbnail((200, 200))  # 缩小图片
                photo = ImageTk.PhotoImage(img)
                self.image_preview.config(image=photo)
                self.image_preview.image = photo  # 保持引用
            except Exception as e:
                self.image_preview.config(text=f"无法预览图片: {str(e)}")
        elif hasattr(self, 'image_preview'):
            self.image_preview.config(image="")
            self.image_preview.image = None
    
    def show_macro_properties(self, macro_item):
        """显示宏命令属性"""
        # 清空现有控件
        for widget in self.properties_frame.winfo_children():
            widget.destroy()
        
        if not macro_item:
            ttk.Label(
                self.properties_frame, 
                text="请在左侧列表中选择一个宏命令查看其属性"
            ).pack(anchor=tk.CENTER, expand=True)
            return
        
        # 显示宏命令类型
        ttk.Label(self.properties_frame, text=f"类型: {macro_item.type}").pack(anchor=tk.W, padx=5, pady=2)
        
        # 根据不同类型显示不同属性
        if hasattr(macro_item, 'key') and hasattr(macro_item, 'action_type') and macro_item.type == "keyboard":
            ttk.Label(self.properties_frame, text=f"按键: {macro_item.key}").pack(anchor=tk.W, padx=5, pady=2)
            ttk.Label(self.properties_frame, text=f"操作类型: {macro_item.action_type}").pack(anchor=tk.W, padx=5, pady=2)
            
        elif hasattr(macro_item, 'content'):
            ttk.Label(self.properties_frame, text=f"内容: {macro_item.content}").pack(anchor=tk.W, padx=5, pady=2)
            
        elif hasattr(macro_item, 'x') and hasattr(macro_item, 'y'):
            ttk.Label(self.properties_frame, text=f"X坐标: {macro_item.x}").pack(anchor=tk.W, padx=5, pady=2)
            ttk.Label(self.properties_frame, text=f"Y坐标: {macro_item.y}").pack(anchor=tk.W, padx=5, pady=2)
            
        elif hasattr(macro_item, 'src'):
            ttk.Label(self.properties_frame, text=f"图片路径: {os.path.basename(macro_item.src)}").pack(anchor=tk.W, padx=5, pady=2)
            ttk.Label(self.properties_frame, text=f"灰度匹配: {'是' if macro_item.grayscale else '否'}").pack(anchor=tk.W, padx=5, pady=2)
            ttk.Label(self.properties_frame, text=f"置信度: {macro_item.confidence}").pack(anchor=tk.W, padx=5, pady=2)
            
            # 显示图片缩略图
            if os.path.exists(macro_item.src):
                try:
                    img = Image.open(macro_item.src)
                    img.thumbnail((200, 200))
                    photo = ImageTk.PhotoImage(img)
                    ttk.Label(self.properties_frame, image=photo).pack(anchor=tk.W, padx=5, pady=5)
                    self.properties_frame.image = photo  # 保持引用
                except Exception as e:
                    ttk.Label(self.properties_frame, text=f"无法预览图片: {str(e)}").pack(anchor=tk.W, padx=5, pady=2)
            
        elif hasattr(macro_item, 'button'):
            ttk.Label(self.properties_frame, text=f"鼠标按键: {macro_item.button}").pack(anchor=tk.W, padx=5, pady=2)
            ttk.Label(self.properties_frame, text=f"操作类型: {macro_item.action_type}").pack(anchor=tk.W, padx=5, pady=2)
            
        elif hasattr(macro_item, 'amount'):
            direction = "下滚" if macro_item.amount > 0 else "上滚"
            ttk.Label(self.properties_frame, text=f"滚动方向: {direction}").pack(anchor=tk.W, padx=5, pady=2)
            ttk.Label(self.properties_frame, text=f"滚动量: {abs(macro_item.amount)}").pack(anchor=tk.W, padx=5, pady=2)
            
        elif hasattr(macro_item, 'milliseconds'):
            ttk.Label(self.properties_frame, text=f"等待时间: {macro_item.milliseconds} 毫秒").pack(anchor=tk.W, padx=5, pady=2)
            
        elif hasattr(macro_item, 'key') and macro_item.type == "wait_key":
            ttk.Label(self.properties_frame, text=f"等待按键: {macro_item.key}").pack(anchor=tk.W, padx=5, pady=2)
    
    def show_run_macro_properties(self, macro_item):
        """显示当前执行项属性"""
        for widget in self.run_properties_frame.winfo_children():
            widget.destroy()

        if not macro_item:
            ttk.Label(
                self.run_properties_frame,
                text="当前无执行项"
            ).pack(anchor=tk.CENTER, expand=True)
            return

        ttk.Label(self.run_properties_frame, text=f"类型: {macro_item.type}").pack(anchor=tk.W, padx=5, pady=2)

        if hasattr(macro_item, 'key') and hasattr(macro_item, 'action_type') and macro_item.type == "keyboard":
            ttk.Label(self.run_properties_frame, text=f"按键: {macro_item.key}").pack(anchor=tk.W, padx=5, pady=2)
            ttk.Label(self.run_properties_frame, text=f"操作类型: {macro_item.action_type}").pack(anchor=tk.W, padx=5, pady=2)
        elif hasattr(macro_item, 'content'):
            ttk.Label(self.run_properties_frame, text=f"内容: {macro_item.content}").pack(anchor=tk.W, padx=5, pady=2)
        elif hasattr(macro_item, 'x') and hasattr(macro_item, 'y'):
            ttk.Label(self.run_properties_frame, text=f"X坐标: {macro_item.x}").pack(anchor=tk.W, padx=5, pady=2)
            ttk.Label(self.run_properties_frame, text=f"Y坐标: {macro_item.y}").pack(anchor=tk.W, padx=5, pady=2)
        elif hasattr(macro_item, 'src'):
            ttk.Label(self.run_properties_frame, text=f"图片路径: {os.path.basename(macro_item.src)}").pack(anchor=tk.W, padx=5, pady=2)
            ttk.Label(self.run_properties_frame, text=f"灰度匹配: {'是' if macro_item.grayscale else '否'}").pack(anchor=tk.W, padx=5, pady=2)
            ttk.Label(self.run_properties_frame, text=f"置信度: {macro_item.confidence}").pack(anchor=tk.W, padx=5, pady=2)
        elif hasattr(macro_item, 'button'):
            ttk.Label(self.run_properties_frame, text=f"鼠标按键: {macro_item.button}").pack(anchor=tk.W, padx=5, pady=2)
            ttk.Label(self.run_properties_frame, text=f"操作类型: {macro_item.action_type}").pack(anchor=tk.W, padx=5, pady=2)
        elif hasattr(macro_item, 'amount'):
            direction = "下滚" if macro_item.amount > 0 else "上滚"
            ttk.Label(self.run_properties_frame, text=f"滚动方向: {direction}").pack(anchor=tk.W, padx=5, pady=2)
            ttk.Label(self.run_properties_frame, text=f"滚动量: {abs(macro_item.amount)}").pack(anchor=tk.W, padx=5, pady=2)
        elif hasattr(macro_item, 'milliseconds'):
            ttk.Label(self.run_properties_frame, text=f"等待时间: {macro_item.milliseconds} 毫秒").pack(anchor=tk.W, padx=5, pady=2)
        elif hasattr(macro_item, 'key') and macro_item.type == "wait_key":
            ttk.Label(self.run_properties_frame, text=f"等待按键: {macro_item.key}").pack(anchor=tk.W, padx=5, pady=2)
    
    def update_edit_list(self, items):
        """更新编辑模式下的宏命令列表"""
        self.edit_listbox.delete(0, tk.END)
        for i, item in enumerate(items):
            self.edit_listbox.insert(tk.END, f"{i+1}. {item.get_display_text()}")
    
    def update_macro_list(self, items):
        """更新执行模式下的宏命令列表"""
        self.macro_listbox.delete(0, tk.END)
        for i, item in enumerate(items):
            self.macro_listbox.insert(tk.END, f"{i+1}. {item.get_display_text()}")
    
    def update_recent_menu(self, recent_projects):
        """更新最近文件菜单"""
        # 清空现有菜单项
        self.recent_menu.delete(0, tk.END)
        
        # 添加最近文件
        if recent_projects:
            for path in recent_projects:
                self.recent_menu.add_command(
                    label=os.path.basename(path),
                    command=lambda p=path: self.controller.open_recent_project(p)
                )
        else:
            self.recent_menu.add_command(label="无最近文件", state=tk.DISABLED)
    
    def log(self, message, is_error=False):
        """添加日志信息"""
        self.log_text.config(state=tk.NORMAL)
        
        # 添加时间戳
        from datetime import datetime
        timestamp = datetime.now().strftime("%H:%M:%S")
        
        # 错误信息显示为红色
        if is_error:
            self.log_text.insert(tk.END, f"[{timestamp}] 错误: {message}\n", "error")
        else:
            self.log_text.insert(tk.END, f"[{timestamp}] {message}\n")
        
        # 自动滚动到底部
        self.log_text.see(tk.END)
        self.log_text.config(state=tk.DISABLED)
        
        # 配置错误标签样式
        self.log_text.tag_config("error", foreground="red")
    
    def create_screenshot_window(self, on_press, on_drag, on_release):
        """创建截图窗口"""
        screenshot_window = tk.Toplevel(self)
        screenshot_window.attributes("-fullscreen", True)
        screenshot_window.attributes("-alpha", 0.3)
        screenshot_window.attributes("-topmost", True)
        screenshot_window.configure(bg="black")
        
        # 创建画布
        canvas = tk.Canvas(screenshot_window, cursor="cross")
        canvas.pack(fill=tk.BOTH, expand=True)
        
        # 绑定鼠标事件
        canvas.bind("<ButtonPress-1>", on_press)
        canvas.bind("<B1-Motion>", on_drag)
        canvas.bind("<ButtonRelease-1>", on_release)
        
        # 显示提示信息
        canvas.create_text(
            self.winfo_screenwidth()//2, self.winfo_screenheight()//2,
            text="拖动鼠标选择截图区域，按ESC取消",
            fill="white",
            # font=("SimHei", 16)
        )
        
        # 绑定ESC键取消
        screenshot_window.bind("<Escape>", lambda e: screenshot_window.destroy())
        
        return screenshot_window, canvas
    
    def bind_shortcuts(self):
        """绑定快捷键"""
        # Ctrl+N 新建
        self.bind("<Control-n>", lambda e: self.controller.new_project())
        # Ctrl+O 打开
        self.bind("<Control-o>", lambda e: self.controller.open_project())
        # Ctrl+S 保存
        self.bind("<Control-s>", lambda e: self.controller.save_project())
        # Ctrl+Shift+S 另存为
        self.bind("<Control-Shift-S>", lambda e: self.controller.save_project_as())
        # Ctrl+Z 撤销
        self.bind("<Control-z>", lambda e: self.controller.undo_action())
        # Ctrl+X 剪切
        self.bind("<Control-x>", lambda e: self.controller.cut_action())
        # Ctrl+C 复制
        self.bind("<Control-c>", lambda e: self.controller.copy_action())
        # Ctrl+V 粘贴
        self.bind("<Control-v>", lambda e: self.controller.paste_action())
        # Ctrl+E 编辑模式
        self.bind("<Control-e>", lambda e: self.controller.switch_mode("edit"))
        # Ctrl+R 执行模式
        self.bind("<Control-r>", lambda e: self.controller.switch_mode("run"))
        # 删除键
        self.bind("<Delete>", lambda e: self.controller.delete_selected_item())
        # F8 获取当前鼠标位置
        self.bind("<F8>", lambda e: self.controller.get_current_mouse_pos())
    
    def show_message(self, title, message, message_type="info"):
        """显示消息对话框"""
        icon_path = os.path.join(os.path.dirname(__file__), "icon.ico")
        # 创建自定义顶层窗口用于设置图标
        top = tk.Toplevel(self)
        top.withdraw()
        top.iconbitmap(icon_path)
        if message_type == "info":
            messagebox.showinfo(title, message, parent=top)
        elif message_type == "warning":
            messagebox.showwarning(title, message, parent=top)
        elif message_type == "error":
            messagebox.showerror(title, message, parent=top)
        elif message_type == "yesno":
            result = messagebox.askyesno(title, message, parent=top)
            top.destroy()
            return result
        elif message_type == "yesnocancel":
            result = messagebox.askyesnocancel(title, message, parent=top)
            top.destroy()
            return result
        top.destroy()
    
    def ask_file_path(self, title, filetypes, save=False):
        """询问文件路径"""
        icon_path = os.path.join(os.path.dirname(__file__), "icon.ico")
        top = tk.Toplevel(self)
        top.withdraw()
        top.iconbitmap(icon_path)
        if save:
            return filedialog.asksaveasfilename(
                title=title,
                defaultextension=".json",
                filetypes=filetypes
            )
        else:
            return filedialog.askopenfilename(
                title=title,
                filetypes=filetypes
            )
        top.destroy()
        return result
    
    def on_close(self):
        """关闭窗口时的处理"""
        # 询问是否保存当前工程
        if self.controller.model.current_project and self.controller.model.get_macro_items():
            response = self.show_message("保存", "是否保存当前宏工程?", "yesnocancel")
            if response is None:  # 取消
                return
            if response:  # 是
                if not self.controller.save_project():
                    return
        
        self.destroy()
